package com.imooc.springcloud.自定义广播消息;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
public class MyBusController {

    @Autowired
    ApplicationContext applicationContext;

    @Autowired
    ApplicationEventPublisher eventPublisher;


    @PostMapping("/bus/publish/myevent")
    public boolean publishMyEvent(@RequestBody EventBody  body) {
        MyEvent event = new MyEvent(body, applicationContext.getId(), "");
        try {
            // 可以注入ApplicationEventPublisher来发送event
            eventPublisher.publishEvent(event);
            log.info(String.valueOf("myevent"+event));
            // 也可以直接使用
            // applicationContext.publishEvent(event)
            return true;
        } catch (Exception e) {
            log.error("failed in publishing event", e);
        }
        return false;
    }

}
